﻿#coding:utf-8
require 'rubygems'
require 'httpclient'
require 'nokogiri'

class PictureToStr
	def send_picture(site, form)
		code_client = HTTPClient.new
		res = code_client.post site, form
		raise res.status if res.status != 200
		res
	end
	
	def find_str(html, css_selector)
			code_str = Nokogiri::HTML(html).css(css_selector)[0].content
			
			if code_str =~ /_/ then 
				raise 'pic code contain _, it must be faild!!'
			end
          
			code_str.gsub!(/[\s|\n]/, '')
	end
end


class PictureToStr_gocr
	def get_str

	system('jpegtopnm.exe 1.jpg > 1.pnm 2>nul')
	system('gocr049.exe -i 1.pnm -o 1.txt ')
	sleep 0.1
	code_str = nil
	File.open('1.txt') {|f| code_str = f.read}
	4.times { code_str = code_str.gsub(/\s/, '').gsub(/\n/, '').gsub(/_/, '').gsub(/!/, '').gsub(/'/,'').gsub(/\//, '') }
	puts "pic code error: #{code_str}"
	if code_str !~/[a-z|A-Z|0-9]{4}/ || code_str.size != 4 then 
		puts "pic code unmatch:#{code_str}"
		code_str = nil
	end

   # code_str=gets()
	code_str
	end
end

class PictureToStr_tesseract
	def get_str
	system('tesseract 1.jpg 1 > nul')
	code_str = nil
	sleep 0.1
	File.open('1.txt') {|f| code_str = f.read}
	4.times { code_str = code_str.gsub(/\s/, '').gsub(/\n/, '').gsub(/_/, '').gsub(/!/, '').gsub(/'/,'').gsub(/\//, '') }
		
	if code_str !~/[a-z|A-Z|0-9]{4}/ || code_str.size != 4 then 
		puts "pic code unmatch:#{code_str}"
		code_str = nil
	end

   # code_str=gets()
	code_str
	end
end


class PictureToStr_newocr < PictureToStr
	def initialize
		@site = 'http://www.newocr.com'
	end
	
	def get_str
		File.open('1.jpg') do |f|
			image_body = {'userfile'=>f,'ocr'=>'ocr','url'=>'', :encType=>'multipart/form-data'}
			res = send_picture(@site, image_body)				
			return find_str(res.content, "textarea#textarea")
		end
	end
end


class PictureToStr_freeocr < PictureToStr
	def initialize
		@site = 'http://www.free-ocr.co.uk/Default.aspx'
	end
	
	def get_str
		File.open('1.jpg') do |f|
			image_body = {'ctl00$cphBody$fileUploader'=>f, 
			'__EVENTVALIDATION'=>"/wEWAgKf0vaeDAKfhMjPAdv92jTv3kjlwQouAbkWG2MjpN8M",
			'__VIEWSTATE'=>"/wEPDwUKLTg2Njk1Nzk2MGRk9DcpBl2V56tUYuGyizp/TrS7omk=", 
			'ctl00$cphBody$btnUpload'=>'Upload'}			
			res = send_picture(@site, image_body)	
			return find_str(res.content,"span#ctl00_cphBody_lblResult")	 
		end
	end
end

class PictureToStr_ocr_extract < PictureToStr
	def initialize
		@site = 'http://www.ocr-extract.com/cgi-bin/weocr/submit.cgi'
	end
	
	def get_str
		File.open('1.jpg') do |f|
			image_body = {'userfile'=>f, 'outputformat'=>'html', 'outputencoding'=>'utf-8', 'contentlang'=>'eng'}	
			res = send_picture(@site, image_body)	
			return find_str(res.content,"div#welcome pre")	 
		end
	end
end




